#!/usr/bin/env python
# coding=utf-8
from bs4 import BeautifulSoup
import re
import chardet
import requests
import json
import MySQLdb
from datetime import  *
import time
class weatherApi:
    def __init__(self):
        now=date.today()
        self.date=now.isoformat()
        self.time=int(time.time())

        pass
    def db(self):
        self.conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="root",db="weather")
        self.cursor=self.conn.cursor()
    def getTime(self):
        self.time=int(time.time())
        return self.time
    def getDate(self):
        now=date.today()
        self.date=now.isoformat()
        return self.date
    def getNow(self,accu_cityid,en_name):
        accu_url="http://www.accuweather.com/zh/cn/luohe/%s/current-weather/%s"%(accu_cityid,accu_cityid)


        weather_now_bs = BeautifulSoup(self.get(accu_url ))

        weather_now_result={"sd":"","qy":"","zwxzs":"","yl":"","ld":"","njd":"","rc":"","rl":"","yc":"",
                            "yunl":"","wd":"","tgwd":"","icon_code":"","fs":"","fl":"","lswd":"","update":"","kqzl":"","shzs":""}
        weather_now_result["update"]=self.getTime()
        weather_now_result_temp=[]
        #当前天气状况，右边栏目
        weather_now_info_right = weather_now_bs.findAll("div", class_="more-info")
        #分别为湿度 气压 紫外线指数 云量 露点 能见度
        for info_li in weather_now_info_right[0].findAll("li"):
            weather_now_result_temp.append(info_li.strong.get_text())

            pass
        weather_now_result["sd"]=[weather_now_result_temp[0],]
        weather_now_result["qy"]=[weather_now_result_temp[1],]
        weather_now_result["zwxzs"]=[weather_now_result_temp[2],]
        weather_now_result["yunl"]=[weather_now_result_temp[3],]
        weather_now_result["ld"]=[weather_now_result_temp[4],]
        weather_now_result["njd"]=[weather_now_result_temp[5],]
        #当前天气情况，左边栏目
        weather_now_info_left=weather_now_bs.findAll("div",class_="forecast")
        #当前天气图标
        icon_code_now=re.findall("icon.+-(\d{1,2})-",str(weather_now_info_left[0]))[0]
        if int(icon_code_now)<10:
            icon_code_now="0"+str(icon_code_now)

        weather_now_result["icon_code"]=[icon_code_now,]
        #分别为 天气 温度 体感温度
        for info_li in weather_now_info_left[0].findAll("span"):


            weather_now_result_temp.append(info_li.get_text())

        weather_now_result["tq"]=[weather_now_result_temp[6],]
        weather_now_result["wd"]=[weather_now_result_temp[7],]
        weather_now_result["tgwd"]=[weather_now_result_temp[9],]
        #日出 日落 日照时间
        weather_feature=weather_now_bs.findAll("p",class_="time-period")
        weather_feature_sun=weather_feature[0]
        weather_feature_moon=weather_feature[1]
        weather_feature_sun_temp=weather_feature_sun.p
        weather_feature_sun_temp =weather_feature_sun.findAll("span")
        weather_feature_moon_temp =weather_feature_moon.findAll("span")
        rc=[weather_feature_sun_temp[1].get_text(),]
        rl=[weather_feature_sun_temp[5].get_text(),]
        rzsj=[weather_feature_sun_temp[3].get_text(),]
        yc=[weather_feature_moon_temp[1].get_text(),]
        yl=[weather_feature_moon_temp[5].get_text(),]
        yzsj=[weather_feature_moon_temp[3].get_text(),]
        weather_now_result["rc"]= rc
        weather_now_result["rl"]= rl
        weather_now_result["rzsj"]= rzsj
        weather_now_result["yc"]= yc
        weather_now_result["yl"]= yl
        weather_now_result["yzsj"]= yzsj
        #历史温度的获取
        weather_history=weather_now_bs.findAll("div",attrs={"id":"feature-history"})
        lswd=[weather_history[0].findAll("tr")[1].td.get_text(),weather_history[0].findAll("tr")[2].td.get_text()]
        weather_now_result ["lswd"]=lswd
        weather_now_result["shzs"]=self.life(accu_cityid)
        weather_now_result["kqzl"]=self.air(en_name)
        return json.dumps(weather_now_result)
        pass
    def getForecast(self,accu_cityid,num):

        weather_forecast_result={"sd":"","qy":"","zwxzs":"","yl":"","ld":"","njd":"","rc":"","rl":"","yc":"",
                    "yunl":"","wd":"","tgwd":"","icon_code":"","fs":"","fl":"","lswd":"","jsgl":"","ly":"","update":"","js":"",
                    "y":"","x":"","bd":""}
        weather_forecast_result["update"]=self.getTime()
        accu_url="http://www.accuweather.com/zh/cn/luohe/%s/daily-weather-forecast/%s?day=%d"%(accu_cityid,accu_cityid,num)

        accu_content=self.get(accu_url )


        bs = BeautifulSoup( accu_content )


        weather_forecast_result_temp=[]
        #未来天气状况
        weather_forecast_info = bs.findAll("div", attrs={"id":"detail-day-night"})
        #图标代码
        icon_code=re.findall("icon.+-(\d{1,2})-",str(weather_forecast_info[0]))
        if int(icon_code[0])<10:
            icon_code[0]="0"+str(icon_code[0])
        if int(icon_code[1])<10:
            icon_code[1]="0"+str(icon_code[1])
        weather_forecast_result["icon_code"]=icon_code
        #天气
        tq_temp= weather_forecast_info [0].findAll("div",class_="desc")
        weather_forecast_result["tq"]=[tq_temp[0].findAll("p")[-1].get_text(),tq_temp[1].findAll("p")[-1].get_text()]
         #白天和晚上状况 分别为风  紫外线指数  雷雨 降水 雨 雪 冰冻
        for info_li in weather_forecast_info[0].findAll("strong"):
            #print info_li.get_text()
            weather_forecast_result_temp.append(info_li.get_text().strip())
            pass
        weather_forecast_result ["fs"]=[weather_forecast_result_temp [0]+u"  阵风 "+weather_forecast_result_temp [1],
                                        weather_forecast_result_temp [8]+u"  阵风 "+weather_forecast_result_temp [9]]
        weather_forecast_result ["zwxzs"]=[weather_forecast_result_temp [2],weather_forecast_result_temp [10]]
        weather_forecast_result ["ly"]=[weather_forecast_result_temp [3],weather_forecast_result_temp [11]]
        weather_forecast_result ["js"]=[weather_forecast_result_temp [4],weather_forecast_result_temp [12]]
        weather_forecast_result ["y"]=[weather_forecast_result_temp [5],weather_forecast_result_temp [13]]
        weather_forecast_result ["x"]=[weather_forecast_result_temp [6],weather_forecast_result_temp [14]]
        weather_forecast_result ["bd"]=[weather_forecast_result_temp [7],weather_forecast_result_temp [15]]
        #历史温度
        weather_history=bs.findAll("div",attrs={"id":"feature-history"})
        lswd=[weather_history[0].findAll("tr")[1].td.get_text(),weather_history[0].findAll("tr")[2].td.get_text()]
        weather_forecast_result ["lswd"]=lswd
        #日出 日落 日照时间 月初 月落 月照时间
        weather_feature=bs.findAll("p",class_="time-period")
        weather_feature_sun=weather_feature[0]
        weather_feature_moon=weather_feature[1]
        weather_feature_sun_temp=weather_feature_sun.p
        weather_feature_sun_temp =weather_feature_sun.findAll("span")
        weather_feature_moon_temp =weather_feature_moon.findAll("span")
        rc=[weather_feature_sun_temp[1].get_text(),]
        rl=[weather_feature_sun_temp[5].get_text(),]
        rzsj=[weather_feature_sun_temp[3].get_text(),]
        yc=[weather_feature_moon_temp[1].get_text(),]
        yl=[weather_feature_moon_temp[5].get_text(),]
        yzsj=[weather_feature_moon_temp[3].get_text(),]
        weather_forecast_result["rc"]= rc
        weather_forecast_result["rl"]= rl
        weather_forecast_result["rzsj"]= rzsj
        weather_forecast_result["yc"]= yc
        weather_forecast_result["yl"]= yl
        weather_forecast_result["yzsj"]= yzsj
        #温度 体感温度 降水概率
        weather_forecast_result_temp1=[]
        for info_li in weather_forecast_info[0].findAll("span"):

                if len(info_li.get_text()) >1 :
                    weather_forecast_result_temp1.append(info_li.get_text() )

        weather_forecast_result["wd"]=[weather_forecast_result_temp1 [1],weather_forecast_result_temp1[5]]
        weather_forecast_result ["tgwd"]=[weather_forecast_result_temp1 [2],weather_forecast_result_temp1[6]]
        weather_forecast_result["jsgl"]=[weather_forecast_result_temp1 [3],weather_forecast_result_temp1[7]]

        return json.dumps(weather_forecast_result)
        pass
    #生活指数
    def life(self,accu_cityid):
        url="http://www.accuweather.com/zh/cn/beijing/%s/weather-forecast/%s"%(accu_cityid,accu_cityid)
        content=self.get(url)
        result={}
        bs=BeautifulSoup(content)
        life_content=bs.findAll("table",attrs={"id":"huafeng-indices"})
        if life_content:
            life_content=life_content[0]
        else:
            return result
        num=99

        for i in life_content.findAll("ul"):
            num=num+1
            result["idx-icon_"+str(num)]=[]
            for li in i.findAll("li"):
                if len(li.get_text()) >1:

                    result["idx-icon_"+str(num)].append(li.get_text())
        return result

    #空气质量
    def air(self,en_name):
        result={}
        result["data"]=[]
        result["desc"]=[]
        url="http://pm25.in/%s"%(en_name.lower() ,)
        content=self.get(url)
        bs=BeautifulSoup(content)
        air_data=bs.findAll("div",class_="span12 data")
        if air_data:
            air_data=air_data[0]
        else :
            return result
        air_desc=bs.findAll("div",class_="span12 caution")
        air_desc=air_desc[0]
        for i in  air_data.findAll("div","span1"):
            name=i.find("div",class_="caption")
            if name :
                name=name.get_text().strip()
                value=i.find("div",class_="value").get_text().strip()
                result["data"].append([name,value])
        for i in air_desc.findAll("p"):

            result["desc"].append(i.get_text().strip())
        return result
    def insert_now(self,cityid,data):
        self.db()
        param=(cityid,self.getDate(),data)
        sql="insert into weather_info(cityid,create_date,now) values(%s,%s,%s)"
        result=self.cursor.execute(sql,param)
        
        return result
        pass
    def update_now(self, id,data):
        self.db()
        param=(data,id,)
        sql="update weather_info set now=%s where id=%s "
        result=self.cursor.execute(sql,param)

        return result
        pass
    def insert_forecast(self,cityid,data):
        self.db()
        param=[]
        param.append(cityid)
        param.append(self.getDate())
        param.extend(data)
        param=tuple(param)


        sql="insert into weather_info(cityid,create_date,day1,day2,day3,day4,day5,day6,day7,day8,day9,day10,day11,day12,day13,day14,day15) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        result=self.cursor.execute(sql,param)

        return result

        pass
    def update_forecast(self,id,data):
        self.db()
        param=[]
        param.extend(data)
        param.append(id)

        param=tuple(param)

        #sql="update weather_info set day1=%s,day2=%s,day3=%s,day4=%s,day5=%s,day6=%s,day7=%s,day8=%s,day9=%s,day10=%s,day11=%s,day12=%s,day13=%s,day14=%s,day15=%s where  id= %s)"
        sql="update weather_info set day1=%s ,day2=%s ,day3=%s ,day4=%s, day5=%s ,day6=%s ,day7=%s ,day8=%s, day9=%s ,day10=%s ,day11=%s ,day12=%s, day13=%s ,day14=%s ,day15=%s  where id=%s"

        result=self.cursor.execute(sql,param)

        return result

        pass
    def getTask(self,type):
        self.db()
        sql="select * from task where type=%s and execute_hour =%s and execute_minute=%s "%(type,time.strftime("%H"),time.strftime("%M"))

        result=self.cursor.execute(sql)
        
        if result :

            return True
        else:
            return False
    def get(self,url):
        return requests.get(url).text
        pass
    def getCity(self):
        self.db()
        sql="select cityid, accu_cityid ,en_name  from city "

        result=self.cursor.execute(sql)
        if result :

            r=self.cursor.fetchall()
            
            return r

        else:
            
            return 0
        pass
    def is_exist(self,cityid,date):
        self.db()
        try:
            sql="select id  from weather_info where cityid=%s and create_date=%s"
            param=(cityid,date)
            result=self.cursor.execute(sql,param)
            if result :

                r=self.cursor.fetchone()
                
                #print r
                return r[0]
            else:
                
                return 0
            pass
        except Exception as e:
            print e


